﻿using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using NTTHAO.CommonWeb;
using NTTHAO.Web.BL.Product;
using NTTHAO.Imaging;
using System.Drawing;
using System.Collections.Generic;

public partial class admin_webparts_Plug_ins_Product_ProductInput : System.Web.UI.UserControl
{
    public ProductType _Type = null;
    public ProductTypeConfig _Config = null;
    public DataTable _CurrencyList = null;
    public Product _Product = null;

    public FileUpload[] GetPropertyFiles(int pIndex)
    {
        switch (pIndex)
        {
            case 1:
                return new FileUpload[] { fuProperty1File1, fuProperty1File2, fuProperty1File3, fuProperty1File4, fuProperty1File5 };
            case 2:
                return new FileUpload[] { fuProperty2File1, fuProperty2File2, fuProperty2File3, fuProperty2File4, fuProperty2File5 };
            case 3:
                return new FileUpload[] { fuProperty3File1, fuProperty3File2, fuProperty3File3, fuProperty3File4, fuProperty3File5 };
            case 4:
                return new FileUpload[] { fuProperty4File1, fuProperty4File2, fuProperty4File3, fuProperty4File4, fuProperty4File5 };
            case 5:
                return new FileUpload[] { fuProperty5File1, fuProperty5File2, fuProperty5File3, fuProperty5File4, fuProperty5File5 };
            case 6:
                return new FileUpload[] { fuProperty6File1, fuProperty6File2, fuProperty6File3, fuProperty6File4, fuProperty6File5 };
            case 7:
                return new FileUpload[] { fuProperty7File1, fuProperty7File2, fuProperty7File3, fuProperty7File4, fuProperty7File5 };
            case 8:
                return new FileUpload[] { fuProperty8File1, fuProperty8File2, fuProperty8File3, fuProperty8File4, fuProperty8File5 };
            case 9:
                return new FileUpload[] { fuProperty9File1, fuProperty9File2, fuProperty9File3, fuProperty9File4, fuProperty9File5 };
            case 10:
                return new FileUpload[] { fuProperty10File1, fuProperty10File2, fuProperty10File3, fuProperty10File4, fuProperty10File5 };
            default:
                return null;
        }
    }
    
    public bool[] GetPropertyFilesRemove(int pIndex)
    {
        bool[] result = new bool[] { false, false, false, false, false };

        for (int i = 0; i < result.Length; i++)
        {
            result[i] = (Request.Params["chkRemoveProperty" + pIndex.ToString() + "File" + (i + 1).ToString()] != null);
        }
        
        return result;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        this.btnSave.Text = this.btnSave2.Text = LanguageUtility.GetLanguageText("SAVE", Session);
        this.chkActive.Text = LanguageUtility.GetLanguageText("ACTIVE", Session);

        string adminCss = "../sites/" + NTTHAO.CommonWeb.WebGlobal.GetSite(Session).SiteID + "/Resources/css/default_admin_product.css";
        if (!System.IO.File.Exists(Server.MapPath(adminCss)))
        {
            adminCss = "../sites/" + NTTHAO.CommonWeb.WebGlobal.GetSite(Session).SiteID + "/Resources/css/default_admin.css";
        }
        if (!System.IO.File.Exists(Server.MapPath(adminCss)))
        {
            adminCss = "../sites/" + NTTHAO.CommonWeb.WebGlobal.GetSite(Session).SiteID + "/Resources/css/default.css";
        }
        this._ContentCKEditor.ContentsCss = adminCss;
        this._ContentCKEditor.Entities = false;
        this._Property1CKEditor.ContentsCss = adminCss;
        this._Property1CKEditor.Entities = false;
        this._Property2CKEditor.ContentsCss = adminCss;
        this._Property2CKEditor.Entities = false;
        this._Property3CKEditor.ContentsCss = adminCss;
        this._Property3CKEditor.Entities = false;
        this._Property4CKEditor.ContentsCss = adminCss;
        this._Property4CKEditor.Entities = false;
        this._Property5CKEditor.ContentsCss = adminCss;
        this._Property5CKEditor.Entities = false;
        this._Property6CKEditor.ContentsCss = adminCss;
        this._Property6CKEditor.Entities = false;
        this._Property7CKEditor.ContentsCss = adminCss;
        this._Property7CKEditor.Entities = false;
        this._Property8CKEditor.ContentsCss = adminCss;
        this._Property8CKEditor.Entities = false;
        this._Property9CKEditor.ContentsCss = adminCss;
        this._Property9CKEditor.Entities = false;
        this._Property10CKEditor.ContentsCss = adminCss;
        this._Property10CKEditor.Entities = false;
        
        try
        {
            DataSet ds = null;
            ds = Currency.GetAll();
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                this._CurrencyList = ds.Tables[0];
                this.cmbCurrency.DataSource = _CurrencyList;
                this.cmbCurrency.DataTextField = Currency.NAME__COLUMN_NAME;
                this.cmbCurrency.DataValueField = Currency.ID__COLUMN_NAME;
                this.cmbCurrency.DataBind();
            }

            int typeID = Int32.Parse(Request.QueryString["typeid"].Trim());
            _Type = new ProductType(typeID);
            _Config = ProductTypeConfig.GetConfigByType(_Type.GroupID, _Type.ID);

            if (_Type.ID < 1 || _Config == null)
            {
                throw new Exception();
            }

            this.txtImageCount.Value = _Config.NumberOfImage.ToString();
            this.txtPropertyCount.Value = _Config.NumberOfProperty.ToString();

            this.BindPropertyData(_Config.Prop1Type, _Config.Prop1CollID, txtProperty1, chkProperty1, _Property1CKEditor);
            this.BindPropertyData(_Config.Prop2Type, _Config.Prop2CollID, txtProperty2, chkProperty2, _Property2CKEditor);
            this.BindPropertyData(_Config.Prop3Type, _Config.Prop3CollID, txtProperty3, chkProperty3, _Property3CKEditor);
            this.BindPropertyData(_Config.Prop4Type, _Config.Prop4CollID, txtProperty4, chkProperty4, _Property4CKEditor);
            this.BindPropertyData(_Config.Prop5Type, _Config.Prop5CollID, txtProperty5, chkProperty5, _Property5CKEditor);
            this.BindPropertyData(_Config.Prop6Type, _Config.Prop6CollID, txtProperty6, chkProperty6, _Property6CKEditor);
            this.BindPropertyData(_Config.Prop7Type, _Config.Prop7CollID, txtProperty7, chkProperty7, _Property7CKEditor);
            this.BindPropertyData(_Config.Prop8Type, _Config.Prop8CollID, txtProperty8, chkProperty8, _Property8CKEditor);
            this.BindPropertyData(_Config.Prop9Type, _Config.Prop9CollID, txtProperty9, chkProperty9, _Property9CKEditor);
            this.BindPropertyData(_Config.Prop10Type, _Config.Prop10CollID, txtProperty10, chkProperty10, _Property10CKEditor);
        }
        catch (Exception)
        {
            Response.Redirect("ProductContent.aspx?action=view&g=" + Request.QueryString["g"] + "&typeid=" + Request.QueryString["typeid"] + "&time=" + DateTime.Now.Ticks.ToString(), false);
            return;
        }
        
        if (!IsPostBack)
        {
            txtInsertDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            for (int i = 0; i < 24; i++)
            {
                cmbInsertHour.Items.Add(new ListItem(i.ToString("00"), i.ToString("00")));
            }
            for (int i = 0; i < 60; i++)
            {
                cmbInsertMin.Items.Add(new ListItem(i.ToString("00"), i.ToString("00")));
            }
            this.cmbInsertHour.Text = DateTime.Now.Hour.ToString("00");
            this.cmbInsertMin.Text = DateTime.Now.Minute.ToString("00");

            try
            {
                this.txtImageCount.Value = _Config.NumberOfImage.ToString();
                this.txtPropertyCount.Value = _Config.NumberOfProperty.ToString();

                if ("proedit".Equals(Request.QueryString["action"], StringComparison.OrdinalIgnoreCase))
                {
                    Product pro = new Product(Int32.Parse(Request.QueryString["id"]));

                    if (pro.ID < 1)
                    {
                        throw new Exception();
                    }
                    this._Product = pro;

                    txtProductID.Text = pro.ProductID;
                    txtName.Text = pro.ProductName;
                    txtDescription.Text = pro.Description;
                    this._ContentCKEditor.Text = pro.Content;
                    txtUnit.Text = pro.Unit;
                    txtPrice.Text = pro.Price.ToString("0");
                    chkSaleOff.Checked = pro.SaleOff;
                    txtSaleOffPrice.Text = pro.SaleOffPrice.ToString("0");
                    chkSoldOut.Checked = pro.SoldOut;
                    cmbCurrency.Value = pro.Currency.ToString();
                    chkActive.Checked = pro.Actived;
                    this.txtInsertDate.Text = pro.InsertDate.ToString("dd/MM/yyyy");
                    this.cmbInsertHour.Text = pro.InsertDate.Hour.ToString("00");
                    this.cmbInsertMin.Text = pro.InsertDate.Minute.ToString("00");

                    this.SetPropertyData(_Config.Prop1Type, pro.Property_1, ";", txtProperty1, chkProperty1, _Property1CKEditor);
                    this.SetPropertyData(_Config.Prop2Type, pro.Property_2, ";", txtProperty2, chkProperty2, _Property2CKEditor);
                    this.SetPropertyData(_Config.Prop3Type, pro.Property_3, ";", txtProperty3, chkProperty3, _Property3CKEditor);
                    this.SetPropertyData(_Config.Prop4Type, pro.Property_4, ";", txtProperty4, chkProperty4, _Property4CKEditor);
                    this.SetPropertyData(_Config.Prop5Type, pro.Property_5, ";", txtProperty5, chkProperty5, _Property5CKEditor);
                    this.SetPropertyData(_Config.Prop6Type, pro.Property_6, ";", txtProperty6, chkProperty6, _Property6CKEditor);
                    this.SetPropertyData(_Config.Prop7Type, pro.Property_7, ";", txtProperty7, chkProperty7, _Property7CKEditor);
                    this.SetPropertyData(_Config.Prop8Type, pro.Property_8, ";", txtProperty8, chkProperty8, _Property8CKEditor);
                    this.SetPropertyData(_Config.Prop9Type, pro.Property_9, ";", txtProperty9, chkProperty9, _Property9CKEditor);
                    this.SetPropertyData(_Config.Prop10Type, pro.Property_10, ";", txtProperty10, chkProperty10, _Property10CKEditor);
                }
                else
                {
                    this.SetPropertyData(_Config.Prop1Type, _Config.Prop1DefaultValue, ";", txtProperty1, chkProperty1, _Property1CKEditor);
                    this.SetPropertyData(_Config.Prop2Type, _Config.Prop2DefaultValue, ";", txtProperty2, chkProperty2, _Property2CKEditor);
                    this.SetPropertyData(_Config.Prop3Type, _Config.Prop3DefaultValue, ";", txtProperty3, chkProperty3, _Property3CKEditor);
                    this.SetPropertyData(_Config.Prop4Type, _Config.Prop4DefaultValue, ";", txtProperty4, chkProperty4, _Property4CKEditor);
                    this.SetPropertyData(_Config.Prop5Type, _Config.Prop5DefaultValue, ";", txtProperty5, chkProperty5, _Property5CKEditor);
                    this.SetPropertyData(_Config.Prop6Type, _Config.Prop6DefaultValue, ";", txtProperty6, chkProperty6, _Property6CKEditor);
                    this.SetPropertyData(_Config.Prop7Type, _Config.Prop7DefaultValue, ";", txtProperty7, chkProperty7, _Property7CKEditor);
                    this.SetPropertyData(_Config.Prop8Type, _Config.Prop8DefaultValue, ";", txtProperty8, chkProperty8, _Property8CKEditor);
                    this.SetPropertyData(_Config.Prop9Type, _Config.Prop9DefaultValue, ";", txtProperty9, chkProperty9, _Property9CKEditor);
                    this.SetPropertyData(_Config.Prop10Type, _Config.Prop10DefaultValue, ";", txtProperty10, chkProperty10, _Property10CKEditor);

                    //this._ContentCKEditor.Text = "<table align=\"center\" border=\"1\" bordercolor=\"#F2f2f2\" cellpadding=\"6\" cellspacing=\"0\" class=\"productdetail\" style=\"border-collapse: collapse\" width=\"100%\"><tr><td align=\"right\" width=\"35%\"><strong><span style=\"color:#ff0000;\">Điều kiện làm việc</span></strong></td><td>&nbsp;</td></tr><tr><td align=\"right\"><strong><span style=\"color:#ff0000;\">Kiểu camera</span></strong></td><td>&nbsp;</td></tr><tr><td align=\"right\"><strong><span style=color:#ff0000;>Độ nhạy sáng</span></strong></td><td>&nbsp;</td></tr><tr><td align=\"right\"><strong><span style=\"color:#ff0000;\">Kích thước cảm biến hình ảnh</span></strong></td><td>&nbsp;</td></tr><tr><td align=\"right\"><strong><span style=\"color:#ff0000;\">Ống kính</span></strong></td><td>&nbsp;</td></tr></table>";
                }
            }
            catch (Exception)
            {
                Response.Redirect("ProductContent.aspx?action=view&g=" + Request.QueryString["g"] + "&typeid=" + Request.QueryString["typeid"] + "&time=" + DateTime.Now.Ticks.ToString(), false);
                return;
            }
        }
    }

    public void BindPropertyData(byte type, int collID, TextBox propertyText, CheckBoxList propertyCheck, CKEditor.NET.CKEditorControl propertyEditor)
    {
        if (type == 1 || type == 5)
        {
            propertyText.Visible = true;
            propertyCheck.Visible = false;
            propertyEditor.Visible = false;
        }
        else if (type == 2 || type == 6)
        {
            propertyText.Visible = false;
            propertyCheck.Visible = true;
            propertyEditor.Visible = false;

            DataTable tbCfg = ProductPropertyCollItem.GetAll(collID, 1);
            if (tbCfg != null)
            {
                propertyCheck.DataSource = tbCfg;
                if (collID == 2 || collID == 4)
                {
                    propertyCheck.DataTextField = ProductPropertyCollItem.VALUE__COLUMN_NAME;
                }
                else
                {
                    propertyCheck.DataTextField = ProductPropertyCollItem.NAME__COLUMN_NAME;
                }
                propertyCheck.DataValueField = ProductPropertyCollItem.ID__COLUMN_NAME;
                propertyCheck.RepeatDirection = RepeatDirection.Horizontal;
                propertyCheck.DataBind();

                for (int i = 0; i < tbCfg.Rows.Count; i++)
                {
                    DataRow row = tbCfg.Rows[i];
                    bool defaultCheck = (bool)row[ProductPropertyCollItem.DEFAULTSELECT__COLUMN_NAME];
                    propertyCheck.Items[i].Selected = defaultCheck;
                }
            }

            if (collID == 2 || collID == 4)
            {
                propertyCheck.RepeatColumns = 4;
                propertyCheck.CssClass = "tbcklist b chkcolor";
                foreach (ListItem item in propertyCheck.Items)
                {
                    item.Attributes["style"] = "background-color: #" + item.Text;
                }
            }
        }
        else if (type == 3 || type == 7)
        {
            propertyText.Visible = false;
            propertyCheck.Visible = false;
            propertyEditor.Visible = false;
        }
        else if (type == 4 || type == 8)
        {
            propertyText.Visible = false;
            propertyCheck.Visible = false;
            propertyEditor.Visible = true;
        }
    }

    public void SetPropertyData(byte type, string value, string valuesSeparator, TextBox propertyText, CheckBoxList propertyCheck, CKEditor.NET.CKEditorControl propertyEditor)
    {
        if (type == 1 || type == 5)
        {
            propertyText.Text = value;
        }
        else if (type == 4 || type == 8)
        {
            propertyEditor.Text = value;
        }
        else
        {
            propertyCheck.ClearSelection();
            if (value == null || value == "")
            {
                return;
            }
            foreach (ListItem item in propertyCheck.Items)
            {
                if (value.IndexOf(valuesSeparator + item.Value + valuesSeparator, StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    item.Selected = true;
                }
            }
        }
    }

    public string GetPropertyData(CheckBoxList propertyCheck, string separator)
    {
        string result = separator;
        foreach (ListItem item in propertyCheck.Items)
        {
            result += item.Selected ? (item.Value + separator) : "";
        }
        if (result.Equals(separator, StringComparison.OrdinalIgnoreCase))
        {
            result = string.Empty;
        }
        return result;
    }

    public string GetPropertyData(int propertyIndex, string currentData, FileUpload[] propertyFiles, bool[] propertyFilesRemove, string path, string separator)
    {
        string[] files = new string[propertyFiles.Length];

        for (int i = 0; i < propertyFiles.Length; i++)
        {
            files[i] = string.Empty;
        }
        
        if (currentData.Length > 0)
        {
            string[] currentDataSpl = currentData.Split(new string[] { separator }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < currentDataSpl.Length; i++)
            {
                files[i] = propertyFilesRemove[i] ? string.Empty : currentDataSpl[i];
                if (propertyFilesRemove[i] && File.Exists(Path.Combine(path, currentDataSpl[i])))
                {
                    try
                    {
                        File.Delete(Path.Combine(path, currentDataSpl[i]));
                    }
                    catch { }
                }
            }
        }
        for (int i = 0; i < propertyFiles.Length; i++)
        {
            if (propertyFiles[i].HasFile && !propertyFilesRemove[i])
            {
                string imageName = "P" + propertyIndex.ToString() + "_" + (i + 1).ToString() + "_" + DateTime.Now.Ticks.ToString() + Path.GetExtension(propertyFiles[i].FileName);
                files[i] = this.SavePropertyImage(propertyFiles[i], path, imageName);
            }
        }
        string result = string.Empty;
        for (int i = 0; i < files.Length; i++)
        {
            if (files[i] != string.Empty)
            {
                result += files[i] + separator;
            }
        }
        if (result.Length > 0)
        {
            result = separator + result;
        }
        return result;
    }

    public string SavePropertyImage(FileUpload fuImage, string path, string imageName)
    {
        try
        {
            if (fuImage.HasFile)
            {
                if (Constant.IMAGE_FILE_EXTENTIONS.Contains(Path.GetExtension(fuImage.PostedFile.FileName).ToLower()))
                {
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    fuImage.SaveAs(Path.Combine(path, imageName));

                    return imageName;
                }
            }
        }
        catch { }
        return string.Empty;
    }

    public string GetPropertyData(int propertyIndex, string currentData, byte type, TextBox propertyText, CheckBoxList propertyCheck, CKEditor.NET.CKEditorControl propertyEditor, FileUpload[] propertyFiles, bool[] propertyFilesRemove, string path)
    {
        if (type == 1 || type == 5)
        {
            return propertyText.Text.Trim();
        }
        else if (type == 2 || type == 6)
        {
            return this.GetPropertyData(propertyCheck, ";");
        }
        else if (type == 3 || type == 7)
        {
            return this.GetPropertyData(propertyIndex, currentData, propertyFiles, propertyFilesRemove, path, ";");
        }
        else if (type == 4 || type == 8)
        {
            return propertyEditor.Text.Trim();
        }
        return string.Empty;
    }

    public string GetCurrentPropertyMultiData(int pIndex, int dIndex)
    {
        if (_Product == null)
        {
            return string.Empty;
        }
        string pData = string.Empty;
        switch (pIndex)
        {
            case 0:
                pData = _Product.Property_1;
                break;
            case 1:
                pData = _Product.Property_2;
                break;
            case 2:
                pData = _Product.Property_3;
                break;
            case 3:
                pData = _Product.Property_4;
                break;
            case 4:
                pData = _Product.Property_5;
                break;
            case 5:
                pData = _Product.Property_6;
                break;
            case 6:
                pData = _Product.Property_7;
                break;
            case 7:
                pData = _Product.Property_8;
                break;
            case 8:
                pData = _Product.Property_9;
                break;
            case 9:
                pData = _Product.Property_10;
                break;
            default:
                return string.Empty;
        }
        pData = pData.Trim();
        if (pData == string.Empty)
        {
            return string.Empty;
        }
        string[] pMultiData = pData.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
        return pMultiData.Length > dIndex ? pMultiData[dIndex] : string.Empty;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            Product pro = null;
            if ("proedit".Equals(Request.QueryString["action"], StringComparison.OrdinalIgnoreCase))
            {
                int id = Int32.Parse(Request.QueryString["id"]);
                pro = new Product(id);
            }
            else if ("proadd".Equals(Request.QueryString["action"], StringComparison.OrdinalIgnoreCase))
            {
                pro = new Product();
                pro.TypeID = Int32.Parse(Request.QueryString["typeid"].Trim());
            }
            else
            {
                throw new Exception();
            }

            pro.ProductID = txtProductID.Text.Trim();
            pro.ProductName = txtName.Text.Trim();
            pro.Description = txtDescription.Text.Trim();
            pro.Content = _ContentCKEditor.Text.Trim();
            pro.Unit = txtUnit.Text.Trim();
            pro.Price = float.Parse(txtPrice.Text.Trim());
            pro.SaleOff = chkSaleOff.Checked;
            pro.SaleOffPrice = pro.SaleOff ? float.Parse(txtSaleOffPrice.Text.Trim()) : pro.Price;
            pro.SoldOut = chkSoldOut.Checked;
            pro.Currency = Int32.Parse(cmbCurrency.Value);
            pro.Actived = chkActive.Checked;
            try
            {
                string[] dSpl = txtInsertDate.Text.Trim().Split(new string[] { "/" }, StringSplitOptions.None);
                int hour = 0;
                int minute = 0;
                int second = pro.ID > 0 ? pro.InsertDate.Second : DateTime.Now.Second;
                Int32.TryParse(cmbInsertHour.SelectedValue.Trim(), out hour);
                Int32.TryParse(cmbInsertMin.SelectedValue.Trim(), out minute);
                pro.InsertDate = new DateTime(Convert.ToInt32(dSpl[2]), Convert.ToInt32(dSpl[1]), Convert.ToInt32(dSpl[0]), hour, minute, second);
            }
            catch { }

            if ("proedit".Equals(Request.QueryString["action"], StringComparison.OrdinalIgnoreCase))
            {
                pro.Update();
            }
            else if ("proadd".Equals(Request.QueryString["action"], StringComparison.OrdinalIgnoreCase))
            {
                pro.Insert();
                pro.ImagePath = "product/" + DateTime.Now.ToString("yyyy/MM") + "/" + pro.ID.ToString("0") + "/";
            }

            string filePath = Server.MapPath("../" + Constant.UPLOAD_FILE_PATH + pro.ImagePath);
            pro.Property_1 = this.GetPropertyData(1, pro.Property_1, _Config.Prop1Type, txtProperty1, chkProperty1, _Property1CKEditor, this.GetPropertyFiles(1), this.GetPropertyFilesRemove(1), filePath);
            pro.Property_2 = this.GetPropertyData(2, pro.Property_2, _Config.Prop2Type, txtProperty2, chkProperty2, _Property2CKEditor, this.GetPropertyFiles(2), this.GetPropertyFilesRemove(2), filePath);
            pro.Property_3 = this.GetPropertyData(3, pro.Property_3, _Config.Prop3Type, txtProperty3, chkProperty3, _Property3CKEditor, this.GetPropertyFiles(3), this.GetPropertyFilesRemove(3), filePath);
            pro.Property_4 = this.GetPropertyData(4, pro.Property_4, _Config.Prop4Type, txtProperty4, chkProperty4, _Property4CKEditor, this.GetPropertyFiles(4), this.GetPropertyFilesRemove(4), filePath);
            pro.Property_5 = this.GetPropertyData(5, pro.Property_5, _Config.Prop5Type, txtProperty5, chkProperty5, _Property5CKEditor, this.GetPropertyFiles(5), this.GetPropertyFilesRemove(5), filePath);
            pro.Property_6 = this.GetPropertyData(6, pro.Property_6, _Config.Prop6Type, txtProperty6, chkProperty6, _Property6CKEditor, this.GetPropertyFiles(6), this.GetPropertyFilesRemove(6), filePath);
            pro.Property_7 = this.GetPropertyData(7, pro.Property_7, _Config.Prop7Type, txtProperty7, chkProperty7, _Property7CKEditor, this.GetPropertyFiles(7), this.GetPropertyFilesRemove(7), filePath);
            pro.Property_8 = this.GetPropertyData(8, pro.Property_8, _Config.Prop8Type, txtProperty8, chkProperty8, _Property8CKEditor, this.GetPropertyFiles(8), this.GetPropertyFilesRemove(8), filePath);
            pro.Property_9 = this.GetPropertyData(9, pro.Property_9, _Config.Prop9Type, txtProperty9, chkProperty9, _Property9CKEditor, this.GetPropertyFiles(9), this.GetPropertyFilesRemove(9), filePath);
            pro.Property_10 = this.GetPropertyData(10, pro.Property_10, _Config.Prop10Type, txtProperty10, chkProperty10, _Property10CKEditor, this.GetPropertyFiles(10), this.GetPropertyFilesRemove(10), filePath);

            this.SaveProductImages(ref pro);

            pro.Update();

            Response.Redirect("ProductContent.aspx?action=view&g=" + Request.QueryString["g"] + "&typeid=" + Request.QueryString["typeid"] + "&time=" + DateTime.Now.Ticks.ToString(), false);
            return;
        }
        catch (Exception)
        {
            Response.Redirect("ProductContent.aspx?action=view&g=" + Request.QueryString["g"] + "&typeid=" + Request.QueryString["typeid"] + "&time=" + DateTime.Now.Ticks.ToString(), false);
            return;
        }
    }

    protected string SaveProductImage(string prefix, int index, string imagePath, string existImage, string chkRemoveImage, FileUpload fuImage)
    {
        if ("1".Equals(chkRemoveImage, StringComparison.OrdinalIgnoreCase))
        {
            if (existImage.Length > 0)
            {
                this.DeleteProductImage(imagePath, existImage);
            }
            return "";
        }
        else if (fuImage.HasFile &&
            Constant.IMAGE_FILE_EXTENTIONS.Contains(Path.GetExtension(fuImage.PostedFile.FileName).ToLower()))
        {
            if (existImage.Length > 0)
            {
                this.DeleteProductImage(imagePath, existImage);
            }
            return this.SaveProductImageFile(
                    fuImage,
                    prefix,
                    index,
                    imagePath,
                    _Config.AutoResizeImage,
                    _Config.MaxImageWidth,
                    _Config.MaxImageHeight,
                    (ResizeOptions)_Config.ImageResizeOption,
                    ColorTranslator.FromHtml("#" + _Config.ImageBackColor),
                    _Config.AutoMiniImage,
                    _Config.MiniImageWidth,
                    _Config.MiniImageHeight,
                    (ResizeOptions)_Config.MiniImageResizeOption,
                    ColorTranslator.FromHtml("#" + _Config.MiniImageBackColor));
        }
        return existImage;
    }

    public void SaveProductImages(ref Product pro)
    {
        string filePath = "../" + Constant.UPLOAD_FILE_PATH + pro.ImagePath;

        string chkRemoveImage1 = Request.Params["chkRemoveImage1"];
        string chkRemoveImage2 = Request.Params["chkRemoveImage2"];
        string chkRemoveImage3 = Request.Params["chkRemoveImage3"];
        string chkRemoveImage4 = Request.Params["chkRemoveImage4"];
        string chkRemoveImage5 = Request.Params["chkRemoveImage5"];
        string chkRemoveImage6 = Request.Params["chkRemoveImage6"];
        string chkRemoveImage7 = Request.Params["chkRemoveImage7"];
        string chkRemoveImage8 = Request.Params["chkRemoveImage8"];
        string chkRemoveImage9 = Request.Params["chkRemoveImage9"];
        string chkRemoveImage10 = Request.Params["chkRemoveImage10"];

        if (!Directory.Exists(Server.MapPath(filePath)))
        {
            Directory.CreateDirectory(Server.MapPath(filePath));
        }

        if (fuPresentativeImage.HasFile &&
            Constant.IMAGE_FILE_EXTENTIONS.Contains(Path.GetExtension(fuPresentativeImage.PostedFile.FileName).ToLower()))
        {
            if (pro.Image.Length > 0)
            {
                this.DeleteProductImage(filePath, pro.Image);
            }
            pro.Image = 
                this.SaveProductImageFile(
                    fuPresentativeImage,
                    pro.UrlName + "-" + pro.ID.ToString(), 
                    0, 
                    filePath, 
                    _Config.ResizePreImage, 
                    _Config.PreImageWidth, 
                    _Config.PreImageHeight, 
                    (ResizeOptions)_Config.PreImageResizeOption, 
                    ColorTranslator.FromHtml("#" + _Config.PreImageBackColor), 
                    false, 
                    -1, 
                    -1,
                    ResizeOptions.AutoFix,
                    Color.White);
        }

        string prefix = pro.UrlName + "-" + pro.ID.ToString();
        pro.Image_1 = this.SaveProductImage(prefix, 1, filePath, pro.Image_1, chkRemoveImage1, fuImage1);
        pro.Image_2 = this.SaveProductImage(prefix, 2, filePath, pro.Image_2, chkRemoveImage2, fuImage2);
        pro.Image_3 = this.SaveProductImage(prefix, 3, filePath, pro.Image_3, chkRemoveImage3, fuImage3);
        pro.Image_4 = this.SaveProductImage(prefix, 4, filePath, pro.Image_4, chkRemoveImage4, fuImage4);
        pro.Image_5 = this.SaveProductImage(prefix, 5, filePath, pro.Image_5, chkRemoveImage5, fuImage5);
        pro.Image_6 = this.SaveProductImage(prefix, 6, filePath, pro.Image_6, chkRemoveImage6, fuImage6);
        pro.Image_7 = this.SaveProductImage(prefix, 7, filePath, pro.Image_7, chkRemoveImage7, fuImage7);
        pro.Image_8 = this.SaveProductImage(prefix, 8, filePath, pro.Image_8, chkRemoveImage8, fuImage8);
        pro.Image_9 = this.SaveProductImage(prefix, 9, filePath, pro.Image_9, chkRemoveImage9, fuImage9);
        pro.Image_10 = this.SaveProductImage(prefix, 10, filePath, pro.Image_10, chkRemoveImage10, fuImage10);
    }

    public void DeleteProductImage(string virtualFilePath, string imageName)
    {
        string currentImage = Path.Combine(Server.MapPath(virtualFilePath), imageName);
        if (File.Exists(currentImage))
        {
            File.Delete(currentImage);
        }
        string currentMiniImage = Path.Combine(Server.MapPath(virtualFilePath), "Mini_" + imageName);
        if (File.Exists(currentMiniImage))
        {
            File.Delete(currentMiniImage);
        }
    }

    public string SaveProductImageFile(
            FileUpload fu, 
            string prefix, 
            int index, 
            string imagePath, 
            bool mustResize, 
            int maxWidth, 
            int maxHeight, 
            ResizeOptions resizeOption, 
            Color backColor,
            bool miniSizeRequired, 
            int miniWidth, 
            int miniHeight,
            ResizeOptions miniResizeOption,
            Color miniBackColor)
    {
        string uploadedFileName = "";

        try
        {
            if (fu.PostedFile != null &&
                Constant.IMAGE_FILE_EXTENTIONS.Contains(Path.GetExtension(fu.PostedFile.FileName).ToLower()))
            {
                uploadedFileName = prefix + "_" + index.ToString() + "_" + DateTime.Now.Ticks.ToString() + Path.GetExtension(fu.PostedFile.FileName);
                string uploadedFilePath = Server.MapPath(imagePath + uploadedFileName);
                if (File.Exists(uploadedFilePath))
                {
                    File.Delete(uploadedFilePath);
                }
                fu.PostedFile.SaveAs(uploadedFilePath);

                if (mustResize)
                {
                    string resizedImagePath = ImageUtilities.ResizeImageToJpeg(uploadedFilePath, maxWidth, maxHeight, resizeOption, backColor, ImageUtilities.HIGHT_PROGRESSIVE);
                    uploadedFileName = Path.GetFileName(resizedImagePath);
                }

                //layer mask
                if (Constant.ADD_LAYER_MASK)
                {
                    float left = 0, top = 0, width = 0, height = 0, opacity = 1;
                    float.TryParse(ConfigValues.GetConfigValue("MASK_TOP_PERCENT").Trim(), out top);
                    float.TryParse(ConfigValues.GetConfigValue("MASK_LEFT_PERCENT").Trim(), out left);
                    float.TryParse(ConfigValues.GetConfigValue("MASK_WIDTH_PERCENT").Trim(), out width);
                    float.TryParse(ConfigValues.GetConfigValue("MASK_HEIGHT_PERCENT").Trim(), out height);
                    float.TryParse(ConfigValues.GetConfigValue("MASK_OPACITY").Trim(), out opacity);
 
                    string desFilePath = Server.MapPath(imagePath + uploadedFileName);
                    desFilePath = ImageUtilities.DrawLayerMask(desFilePath, Server.MapPath("../" + Constant.MASK_IMAGE_FILE), top, left, width, height, ResizeOptions.MaximumSizeFix, opacity, ImageUtilities.HIGHT_PROGRESSIVE);
                    if (desFilePath != null)
                    {
                        uploadedFileName = Path.GetFileName(desFilePath);
                    }
                }
                // end

                if (miniSizeRequired)
                {
                    string miniFilePath = Server.MapPath(imagePath + "Mini_" + uploadedFileName);
                    if (File.Exists(miniFilePath))
                    {
                        File.Delete(miniFilePath);
                    }
                    //fu.PostedFile.SaveAs(miniFilePath);

                    File.Copy(Server.MapPath(imagePath + uploadedFileName), miniFilePath);

                    miniFilePath = ImageUtilities.ResizeImageToJpeg(miniFilePath, miniWidth, miniHeight, miniResizeOption, miniBackColor, ImageUtilities.HIGHT_PROGRESSIVE);
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }

        return uploadedFileName;
    }
}
